<template>
  <t-link theme="primary" @click="handleamountReceivedView">{{props.amountReceived.toFixed(2)}}</t-link>
  <t-dialog v-model:visible="visible" attach="body" header="收款记录" width="60%">
    <custom-table
      ref="customTableRef"
      row-key="id"
      :columns="columns"
      :api="payLogContractZhengCRUD.page"
      column-controller-key="DiscussLogList"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-button
            v-permission="['system:zheng-contract-pay-log:create']"
            @click="handleOpenDialog('create', { 
              fileUrl:[],
              contractPayId: props.collectionId,
              orderId: props.orderId
              })"
          >
            新建收款记录
          </t-button>

    
        </div>
      </template>
      <template #fileUrl="{ row }">
        <image-viewer :images="row.fileUrl.map((f: Record<string, string>) => f.url)" width="80px" height="80px" />
      </template>
      <template #createTime="{ row }">
        {{ row.createTime?dayjs(row.createTime).format('YYYY-MM-DD hh:mm:ss'):'' }}
      </template>  
      <template #operation="{ row }">
        <t-space break-line>
          <!-- <t-link
            v-permission="['system:zheng-contract-pay-log:query']"
            theme="primary"
            @click="handleOpenDialog('read', { id: row.id })"
          >
            详情
          </t-link> -->
          <t-popconfirm content="确认要确认该项吗？" @confirm="handleConfirm({ id: row.id, contractPayId: collectionId })">
            <t-link theme="primary" v-if="row.status==='0'" v-permission="['system:zheng-contract-pay-log:confirm']"> 确认 </t-link>
          </t-popconfirm>
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link theme="danger"  v-permission="['system:zheng-contract-pay-log:delete']"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    
      
    <template #footer>
      <t-button theme="default" @click="visible = false">取消</t-button>
      <!-- <t-button :loading="loadingSubmit" @click="handleSelectedIds">保存</t-button> -->
    </template>
  </t-dialog>
   <!-- 自定义对话框 -->
   <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="payLogContractZhengCRUD"
      header="*收款记录"
      width="30%"
      :on-before-set-data="handleDialogSetData"
      :on-before-save-data="handleDialogSaveData"
      @request-success="handleDialogRequestSuccess"
    > 
      <t-form-item 
        label="收款金额" 
        name="payMoney" 
        :rules="[{ required: true, message: '请输入收款金额' }]">
        <t-input-number 
          v-model:value="formData.payMoney" 
          :min="0" 
          :decimal-places="2" 
          placeholder="请输入收款金额" 
          clearable 
          :readonly="readonly"
          style="width: 50%;"
        />
      </t-form-item>
    
      <t-form-item label="收款凭证" name="fileUrl" :rules="[{ required: true, message: '请上传收款凭证' }]">
        <upload 
          v-model:files="formData.fileUrl" 
          accept="image/*" 
          theme="image" 
          :disabled="readonly"
          multiple
          />
      </t-form-item>
      <t-form-item label="备注" name="remark" :rules="[{ required: true, message: '请输入备注' }]">
        <t-textarea v-model:value="formData.remark" placeholder="请输入备注" clearable :readonly="readonly" />
      </t-form-item>
    </custom-dialog>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { onMounted, ref, useTemplateRef, watch } from 'vue';
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';

import { payContractZhengCRUD } from '@/api/finance/pay';
import { payLogContractZhengCRUD, payLogContractZhengConfirm } from '@/api/finance/pay';

import { getCompanyList } from '@/api/system/dept';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import ImageViewer from '@/components/image-viewer/index.vue';
import Upload from '@/components/upload/index.vue';
import { useDictionaryStore, useUserStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 用户仓库
const userStore = useUserStore();

const props = defineProps({
  collectionId: {
    type: String || Number,
    required: true,
  },
  orderId: {
    type: String,
    required: true,
  },
  paymentStage: {
    type: String,
    required: true,
  },
  amountReceived: {
    type: Number,
    required: true,
  },
});

const emits = defineEmits(['refresh']);

const visible = ref(false);

// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// columns
const columns: TableCol[] = [
  { colKey: 'payMoney', title: '收款金额' },
  { colKey: 'fileUrl', title: '收款凭证' },
  { colKey: 'remark', title: '备注' },
  { colKey: 'createTime', title: '创建时间' },
  { colKey: 'operation', title: '操作', width: 160, fixed: 'right' },
];


// 处理初始化表格
const handleInitTable = () => {
  const params = { 
    contractPayId	: props.collectionId,
    orderId: props.orderId
  };
  customTableRef.value.initTable(params);  
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};


// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
    customDialogRef.value.open(mode, params); 
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 判断是否显示删除按钮
const showDeleteButton = (row:any) => {
  // 如果用户是超级管理员，则显示删除按钮
  if (userStore.userInfo.roles.includes('super_admin')) {
    return true;
  }
  // 如果不是超级管理员，则根据 row.status 判断
  return row.status === '0';
};
const handleamountReceivedView = () => {
  visible.value = true;
  handleInitTable();
}
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  payLogContractZhengCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};

// 处理确认
const handleConfirm = (params: Record<string, any>) => {
  payLogContractZhengConfirm(params)
    .then(() => {
      MessagePlugin.success('确认成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};

// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  params.payMoney = params.payMoney.toFixed(2)
  
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
};

watch(visible, (newVal) => {
  if(newVal===false) {
    emits('refresh');
  }
});
</script>
